<template>
  <div style="width: 100%; height: 100%">


    <!--    <Descriptions size="small" :title="totalTitle"-->
    <!--      style="margin-top: 10px;">-->
    <!--      <DescriptionsItem label="选择创建时间">-->
    <!--        <MonthPicker placeholder="请选择月份" @change="monthChangeFn" format="YYYY-MM"></MonthPicker>-->
    <!--      </DescriptionsItem>-->
    <!--    </Descriptions>-->


    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>

      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>
      <template #state="{ row }">
        <Tag :color="t_paseTags(row).color">{{ t_paseTags(row).val }}</Tag>
      </template>

    </vxe-grid>


    <FormModal @register="registerDrawer" @success="handleSuccess" />

  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  ywApprovalList, ywApprovalCancel, ywApprovalRemove, ywDeptTotalList, getCountDeptTotalLog_biao
} from '@/api/sys/approval';
import {
  approveBack, syncMoneyTable, approveAbolish, getCountDeptTotalLog,
} from '@/api/heng/ywManage';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns,
  vxeTableFormSchema,
  paseTags
} from './role.data';
// import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { Tag, Descriptions, DescriptionsItem } from 'ant-design-vue';
import { reactive, ref, unref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import FormModal from './FormModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button, Timeline, TimelineItem, MonthPicker } from 'ant-design-vue';
import { useDrawer } from "@/components/Drawer";

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

// const [register, { openModal, closeModal }] = useModal();
const [registerDrawer, { openDrawer }] = useDrawer();

const orderModal = useModal();
const loading = ref(false);
const visible = ref(false);
const applyViewShow = ref(false);

const totalObj = ref({ salesmanDeptList: [] })
const totalTitle = ref("");

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },

  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  // console.log("----json:", json);
  // ywApproveList xftList
  form.pageName = "钟部经理提成审批";
  return ywApprovalList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};




function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}

function getUserName(item) {
  let userName = item.userName;
  return userName;
}

//查看审批详情
function applyViewFn(record) {


}

function approveAbolishFn(record: Recordable) {
  //console.log(record);

  ywApprovalRemove(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}

function t_paseTags(row) {
  let val = '';
  let color = '';
  switch (row.status) {
    case 1:
      val = '审批中';
      color = 'orange';
      break;
    case 2:
      val = '已通过';
      color = 'green';

      break;
    case 99:
      val = '已驳回';
      color = 'red';

      break;
    case 0:
      val = '已撤销';
      color = 'red';
      break;
    default:
      break;
  }
  return { color, val };
}


// const showTotalObj=ref(false);
function getCountDeptTotalLogFn(form) {

  getCountDeptTotalLog_biao(form).then((res) => {
    if (res.code == 200) {
      // console.log(res.data);
      // let obj = res.data.;
      totalObj.value.salesmanDeptList = res.data;

      // totalObj.value = obj ? obj : { salesmanDeptList: [] };
      let t = "表部抽成汇总";

      // if (obj && obj.salesmanDeptList) {
      //   t += ":" + obj.salesmanDeptList.join("、");
      //
      // }
      totalTitle.value = t

      //  console.log("---totalObj.value:", totalObj.value);

    } else {
      createMessage.error(res.message);

    }

  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}

onMounted(() => {
  // getCountDeptTotalLogFn(null);
})

function getActions(record) {
  let arr = [];
  let userName = userStore.getUserInfo?.userName;
  let role = userStore.getUserInfo?.role;
  let title = "查看";
  let color = "";
  if (record.status == 1 && record.currentUserName == userName) {
    title = "审批";
    color = "warning"
  }

  arr.push({
    // icon: 'clarity:note-edit-line',
    label: title,
    color,
    onClick: handleEdit.bind(null, record),
  });
  if (record.isCancel && record.isCancel == 1) {

    if (record.userName == userName || role == "manage") {
      arr.push({
        // icon: 'ant-design:delete-outlined',
        label: '撤回',
        color: 'error',
        popConfirm: {
          title: '是否撤回该申请？',
          placement: 'left',
          loading: record.loading,
          confirm: handleClose.bind(null, record),
        },
      });
    }
  }

  if (role == "manage") {
    arr.push({
      // icon: 'ant-design:delete-outlined',
      label: '作废',
      color: 'error',
      popConfirm: {
        title: '是否作废该申请？',
        placement: 'left',
        loading: record.loading,
        confirm: approveAbolishFn.bind(null, record),
      },
    });
  }


  return arr;
}

function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openDrawer(true, {
    record
  });
}

function monthChangeFn(e, r) {
  getCountDeptTotalLogFn(r);
}

function handleClose(record: Recordable) {
  //console.log(record);
  // loading.value = true;
  record.loading = true;
  ywApprovalCancel(record)
    .then((res) => {
      record.loading = false;
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      record.loading = false;
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}


function handleSycnFn(record: Recordable) {
  //console.log(record);

  syncMoneyTable(record)
    .then((res) => {
      if (res.code == 200) {
        if (res.data) {
          createMessage.error(res.data[0].errorMessage);
          return;
        } else {
          createMessage.success(res.message);
          tableRef.value.commitProxy('reload');
        }


      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      // createMessage.error(res.message);
    })
    .finally(() => {
    });
}

function handleSuccess() {
  tableRef.value.commitProxy('reload');
}


function openUserModal(record: Recordable, type) {
  record.openType = type; // type 1 看符合退款条件的数据 2 看已有的数据
  orderModal[1].openModal(true, record);
}


</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}

.count-i {
  width: 200px;
  margin-top: 8px;
}

.count-i-p {
  color: #c65206;
}
</style>
